package ua.senfiron.finder.searchengine;

import org.apache.commons.lang3.StringEscapeUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import ua.senfiron.finder.R;
import ua.senfiron.finder.SearchResultItem;
import ua.senfiron.finder.util.HttpUtilities;
import android.net.Uri;

public class BingWebSearchEngine extends AbstractSearchEngine {

    private static final String ENGINE_NAME = "Bing Web Search";
    private static final int ENGINE_ICON_RES_ID = R.drawable.bing_icon;
    private static final String ACCOUNT_KEY = "7VYk5sd4fLklUtiVHkghZxLXWyEjxpXk/2xwlT+F7bQ=";
    private static final String BASE_URL = "https://api.datamarket.azure.com/Bing/Search/v1/Composite";

    @Override
    public String getEngineName() {
        return ENGINE_NAME;
    }

    @Override
    public int getIconResID() {
        return ENGINE_ICON_RES_ID;
    }
    
    @Override
    public int loadResults(int maxCount) {     
        
        int count = 0;
        while(count < maxCount)
        {
            if(isCanceled())
                break;
            
            Uri.Builder builder = Uri.parse(BASE_URL).buildUpon();
            builder.appendQueryParameter("$format", "json");
            builder.appendQueryParameter("Sources", "'web+spell'");
            builder.appendQueryParameter("Query", "'" + mQuery + "'");
            builder.appendQueryParameter("$skip", String.valueOf(count));
            
            String jsonResponseString = null;
            jsonResponseString = HttpUtilities.getData(builder.build(), "ignored",
                        ACCOUNT_KEY);

            try {
    
                JSONObject json = new JSONObject(jsonResponseString);
                int totalCount = json.getJSONObject("d").getJSONArray("results")
                        .getJSONObject(0).getInt("WebTotal");
                if(totalCount < maxCount)
                {
                    maxCount = totalCount;
                    if(mListener != null)
                        mListener.onMaxResultsCountChanged(maxCount);
                }
                JSONArray results = null;
                results = json.getJSONObject("d").getJSONArray("results")
                        .getJSONObject(0).getJSONArray("Web");
    
                for (int j = 0; j < results.length() && count < maxCount; j++, count++) {
                    if(isCanceled())
                        break;
                    JSONObject curResult = results.getJSONObject(j);
    
                    String title = StringEscapeUtils.unescapeHtml4(curResult
                            .getString("Title"));
                    String url = StringEscapeUtils.unescapeHtml4(curResult
                            .getString("Url"));
                    
                    SearchResultItem result = 
                            new SearchResultItem(title,url,getEngineName(),getIconResID());
                    if(mListener != null)
                        mListener.onSerachResultLoaded(result);
                }
            } catch (JSONException e) {
                e.printStackTrace();
                if(mListener != null)
                    mListener.onMaxResultsCountChanged(count);
                break;
            }
        }
        return count;
    }
}

